$(document).ready(function() {
    // 初始化分页和数据
    initPaginationAndData();

    // 保存订单按钮点击事件
    $('#saveOrderBtn').click(function() {
        const orderNumber = $('#orderNumber').val();
        const customerName = $('#customerName').val();
        const orderAmount = $('#orderAmount').val();
        const orderStatus = $('#orderStatus').val();
        const orderDate = $('#orderDate').val();

        // 表单验证
        if (!orderNumber || !customerName || !orderAmount || !orderStatus || !orderDate) {
            alert('请填写所有必填字段！');
            return;
        }
        if (!/^\d+$/.test(orderNumber)) {
            alert('订单编号必须为数字！');
            return;
        }
        if (isNaN(orderAmount) || parseFloat(orderAmount) < 0) {
            alert('订单金额必须为有效的正数！');
            return;
        }

        const data = {
            orderNumber: orderNumber,
            customerName: customerName,
            orderAmount: orderAmount,
            orderStatus: orderStatus,
            orderDate: orderDate
        };

        $.ajax({
            url: '/add_order',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(data),
            success: function(response) {
                if (response.success) {
                    alert('订单添加成功');
                    initPaginationAndData();
                } else {
                    alert('订单添加失败：' + response.message);
                }
            },
            error: function(error) {
                alert('请求出错：' + error.statusText);
            }
        });
    });

    // 编辑按钮点击事件
    $('tbody').on('click', '.btn-warning', function() {
        const $tr = $(this).closest('tr');
        const orderId = $tr.find('td').eq(1).text();
        const customerName = $tr.find('td').eq(2).text();
        const orderAmount = $tr.find('td').eq(3).text().replace('￥', '');
        const orderStatusClass = $tr.find('td').eq(4).find('span').attr('class');
        const orderStatus = orderStatusClass.includes('processing') ? 'processing' :
            orderStatusClass.includes('completed') ? 'completed' : 'cancelled';
        const orderDate = $tr.find('td').eq(5).text();

        $('#editOrderId').val(orderId);
        $('#editCustomerName').val(customerName);
        $('#editOrderAmount').val(orderAmount);
        $('#editOrderStatus').val(orderStatus);
        $('#editOrderDate').val(orderDate);

        $('#editOrderModal').modal('show');
    });

    // 保存编辑按钮点击事件
    $('#saveEditOrderBtn').click(function() {
        const orderId = $('#editOrderId').val();
        const customerName = $('#editCustomerName').val();
        const orderAmount = $('#editOrderAmount').val();
        const orderStatus = $('#editOrderStatus').val();
        const orderDate = $('#editOrderDate').val();

        // 表单验证
        if (!customerName || !orderAmount || !orderStatus || !orderDate) {
            alert('请填写所有必填字段！');
            return;
        }
        if (isNaN(orderAmount) || parseFloat(orderAmount) < 0) {
            alert('订单金额必须为有效的正数！');
            return;
        }

        const data = {
            orderId: orderId,
            customerName: customerName,
            orderAmount: orderAmount,
            orderStatus: orderStatus,
            orderDate: orderDate
        };

        $.ajax({
            url: '/edit_order',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(data),
            success: function(response) {
                if (response.success) {
                    alert('订单编辑成功');
                    initPaginationAndData();
                } else {
                    alert('订单编辑失败：' + response.message);
                }
            },
            error: function(error) {
                alert('请求出错：' + error.statusText);
            }
        });
    });

    // 删除按钮事件委托
    $('tbody').on('click', '.btn-danger', function() {
        if (confirm('确定要删除这个订单吗？')) {
            const orderId = $(this).closest('tr').find('td').eq(1).text();
            const data = {
                orderId: orderId
            };

            $.ajax({
                url: '/delete_order',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(data),
                success: function(response) {
                    if (response.success) {
                        alert('订单删除成功');
                        initPaginationAndData();
                    } else {
                        alert('订单删除失败：' + response.message);
                    }
                },
                error: function(error) {
                    alert('请求出错：' + error.statusText);
                }
            });
        }
    });

    // 搜索功能
    $('#searchInput').on('keyup', function() {
        const searchText = $(this).val().toLowerCase();
        const selectedStatus = $('#order-status-filter').val();
        const selectedDate = $('#order-date-filter').val();
        getOrders(1, searchText, selectedStatus, selectedDate);
    });

    // 筛选功能
    $('.btn-primary-custom').on('click', function() {
        if ($(this).text() === '筛选') {
            const searchText = $('#searchInput').val().toLowerCase();
            const selectedStatus = $('#order-status-filter').val();
            const selectedDate = $('#order-date-filter').val();
            getOrders(1, searchText, selectedStatus, selectedDate);
        }
    });

    // 重置筛选
    $('.btn-secondary-custom').on('click', function() {
        if ($(this).text() === '重置') {
            $('#order-status-filter').val('all');
            $('#order-date-filter').val('');
            const searchText = $('#searchInput').val().toLowerCase();
            const selectedStatus = $('#order-status-filter').val();
            const selectedDate = $('#order-date-filter').val();
            getOrders(1, searchText, selectedStatus, selectedDate);
        }
    });

    // 批量导入订单按钮点击事件
    $('#importOrdersBtn').click(function() {
        const fileInput = $('#importOrderFile')[0];
        const file = fileInput.files[0];
        if (file) {
            const formData = new FormData();
            formData.append('file', file);

            $.ajax({
                url: '/import_orders',
                type: 'POST',
                data: formData,
                contentType: false,
                processData: false,
                success: function(response) {
                    if (response.success) {
                        alert(`成功导入 ${response.importedCount} 个订单数据`);
                        $('#importOrderModal').modal('hide');
                        $('#importOrderFile').val('');
                        initPaginationAndData();
                    } else {
                        alert('订单导入失败：' + response.message);
                    }
                },
                error: function(error) {
                    alert('请求出错：' + error.statusText);
                }
            });
        } else {
            alert('请选择要导入的CSV文件！');
        }
    });

    // 订单数据清理按钮点击事件
    $('#dataCleanOrderBtn').click(function() {
        if (confirm('确认要清理所有订单数据吗？此操作不可恢复。')) {
            $.ajax({
                url: '/clean_orders',
                type: 'POST',
                success: function(response) {
                    if (response.success) {
                        alert('所有订单数据已清理完毕');
                        $('#dataCleanOrderModal').modal('hide');
                        initPaginationAndData();
                    } else {
                        alert('订单数据清理失败：' + response.message);
                    }
                },
                error: function(error) {
                    alert('请求出错：' + error.statusText);
                }
            });
        }
    });

    // 模态框关闭时重置表单
    $('#addOrderModal').on('hidden.bs.modal', function () {
        $('#addOrderForm')[0].reset();
    });
    $('#editOrderModal').on('hidden.bs.modal', function () {
        $('#editOrderForm')[0].reset();
    });
    $('#importOrderModal').on('hidden.bs.modal', function () {
        $('#importOrderFile').val('');
    });
});

// 分页相关变量
var currentPage = 1;
var rowsPerPage = 5; // 每页显示5条记录

// 初始化分页和数据
function initPaginationAndData() {
    const searchText = $('#searchInput').val().toLowerCase();
    const selectedStatus = $('#order-status-filter').val();
    const selectedDate = $('#order-date-filter').val();
    getOrders(1, searchText, selectedStatus, selectedDate);
}

// 获取订单数据
function getOrders(page, searchText, selectedStatus, selectedDate) {
    $.ajax({
        url: '/get_orders',
        type: 'GET',
        data: {
            page: page,
            rowsPerPage: rowsPerPage,
            searchText: searchText,
            selectedStatus: selectedStatus,
            selectedDate: selectedDate
        },
        success: function(response) {
            if (response.success) {
                const orders = response.orders;
                const totalPages = response.totalPages;
                const totalRecords = response.totalRecords;

                // 清空表格
                $('tbody').empty();

                // 填充表格数据
                orders.forEach((order, index) => {
                    const newRow = `
                        <tr>
                            <td>${(page - 1) * rowsPerPage + index + 1}</td>
                            <td>${order.orderNumber}</td>
                            <td>${order.customerName}</td>
                            <td>￥${order.orderAmount}</td>
                            <td><span class="order-status order-status-${order.orderStatus}">${getStatusText(order.orderStatus)}</span></td>
                            <td>${order.orderDate}</td>
                            <td>
                                <button class="btn btn-sm btn-primary-custom view-detail-btn">查看详情</button>
                                <button class="btn btn-sm btn-warning">编辑</button>
                                <button class="btn btn-sm btn-danger">删除</button>
                            </td>
                        </tr>
                    `;
                    $('tbody').append(newRow);
                });

                // 更新分页信息
                currentPage = page;
                updatePaginationInfo(totalPages, totalRecords);
            } else {
                alert('获取订单数据失败：' + response.message);
            }
        },
        error: function(error) {
            alert('请求出错：' + error.statusText);
        }
    });
}

// 更新分页信息
function updatePaginationInfo(totalPages, totalRecords) {
    $("#currentPageInfo").text(`当前第 ${currentPage} 页，共 ${totalPages} 页，总计 ${totalRecords} 条记录`);
    renderPaginationButtons(totalPages);
}

// 渲染分页按钮
function renderPaginationButtons(totalPages) {
    const paginationContainer = $('.pagination-buttons');
    paginationContainer.empty();

    // 最多显示5个页码按钮
    let startPage = Math.max(1, currentPage - 2);
    let endPage = Math.min(totalPages, currentPage + 2);

    if (currentPage <= 3) {
        endPage = Math.min(5, totalPages);
    }
    if (currentPage >= totalPages - 2) {
        startPage = Math.max(1, totalPages - 4);
    }

    // 第一页按钮
    if (startPage > 1) {
        const firstBtn = $('<button>').text('1').addClass('btn btn-page').click(() => getOrders(1, $('#searchInput').val().toLowerCase(), $('#order-status-filter').val(), $('#order-date-filter').val()));
        paginationContainer.append(firstBtn);

        if (startPage > 2) {
            const ellipsis = $('<span>').text('...').addClass('px-2');
            paginationContainer.append(ellipsis);
        }
    }

    // 中间页码按钮
    for (let i = startPage; i <= endPage; i++) {
        const pageBtn = $('<button>')
            .text(i)
            .addClass('btn btn-page' + (i === currentPage ? ' bg-blue-500 text-white' : ''))
            .click(() => getOrders(i, $('#searchInput').val().toLowerCase(), $('#order-status-filter').val(), $('#order-date-filter').val()));
        paginationContainer.append(pageBtn);
    }

    // 最后一页按钮
    if (endPage < totalPages) {
        if (endPage < totalPages - 1) {
            const ellipsis = $('<span>').text('...').addClass('px-2');
            paginationContainer.append(ellipsis);
        }

        const lastBtn = $('<button>').text(totalPages).addClass('btn btn-page').click(() => getOrders(totalPages, $('#searchInput').val().toLowerCase(), $('#order-status-filter').val(), $('#order-date-filter').val()));
        paginationContainer.append(lastBtn);
    }
}

// 上一页
function prevPage() {
    if (currentPage > 1) {
        const searchText = $('#searchInput').val().toLowerCase();
        const selectedStatus = $('#order-status-filter').val();
        const selectedDate = $('#order-date-filter').val();
        getOrders(currentPage - 1, searchText, selectedStatus, selectedDate);
    }
}

// 下一页
function nextPage() {
    const totalPages = Math.ceil($('tbody tr').length / rowsPerPage);
    if (currentPage < totalPages) {
        const searchText = $('#searchInput').val().toLowerCase();
        const selectedStatus = $('#order-status-filter').val();
        const selectedDate = $('#order-date-filter').val();
        getOrders(currentPage + 1, searchText, selectedStatus, selectedDate);
    }
}

// 获取状态文本
function getStatusText(status) {
    switch(status) {
        case 'processing': return '处理中';
        case 'completed': return '已完成';
        case 'cancelled': return '已取消';
        default: return status;
    }
}

// 高级操作下拉菜单
document.getElementById('advancedActionsBtn').addEventListener('click', function() {
    document.getElementById('advancedActionsDropdown').classList.toggle('hidden');
});

// 点击其他地方关闭下拉菜单
document.addEventListener('click', function(event) {
    if (!event.target.closest('.dropdown')) {
        document.getElementById('advancedActionsDropdown').classList.add('hidden');
    }
});

// 查看详情按钮事件
$(document).on('click', '.view-detail-btn', function() {
    const row = $(this).closest('tr');
    $('#detailOrderNumber').text(row.find('td').eq(1).text());
    $('#detailCustomerName').text(row.find('td').eq(2).text());
    $('#detailOrderAmount').text(row.find('td').eq(3).text());
    $('#detailOrderStatus').text(row.find('td').eq(4).text());
    $('#detailOrderDate').text(row.find('td').eq(5).text());

    const modal = new bootstrap.Modal(document.getElementById('orderDetailModal'));
    modal.show();
});

// 导出订单数据按钮点击事件
$('.btn-primary-custom').eq(0).click(function() {
    $.ajax({
        url: '/export_orders',
        type: 'GET',
        success: function(response) {
            if (response.success) {
                const exportData = response.exportData;
                $('#exportOrderData').text(exportData);
                $('#exportOrderModal').modal('show');
            } else {
                alert('导出订单数据失败：' + response.message);
            }
        },
        error: function(error) {
            alert('请求出错：' + error.statusText);
        }
    });
});

// 生成订单报告按钮点击事件
$('.btn-success').click(function() {
    $.ajax({
        url: '/generate_report',
        type: 'GET',
        success: function(response) {
            if (response.success) {
                const report = response.report;
                $('#generateReportData').text(report);
                $('#generateReportModal').modal('show');
            } else {
                alert('生成订单报告失败：' + response.message);
            }
        },
        error: function(error) {
            alert('请求出错：' + error.statusText);
        }
    });
});